from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI
import sys
import signal

# 初始化Flask应用
app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 初始化OpenAI客户端
client = OpenAI(
    base_url='https://api.deepseek.com',  # 自定义API端点
    api_key='your-api-key-here'             # 替换为您的API密钥
)

# 存储全局对话历史
global_messages = [
    {"role": "system", "content": "你是一个乐于助人的助手。"}
]


@app.route('/chat', methods=['POST'])
def chat():
    global global_messages

    # 获取请求数据
    data = request.json
    messages = data.get('messages', global_messages)

    try:
        # 调用API获取助手回复
        completion = client.chat.completions.create(
            model="deepseek-chat",  # 使用的模型
            messages=messages
        )

        # 提取助手的回复
        assistant_reply = completion.choices[0].message.content

        # 更新全局对话历史
        global_messages = messages.copy()
        global_messages.append({"role": "assistant", "content": assistant_reply})

        return jsonify({"reply": assistant_reply, "status": "success"})

    except Exception as e:
        print(f"错误: {str(e)}")
        return jsonify({"reply": f"发生错误: {str(e)}", "status": "error"}), 500


@app.route('/quit', methods=['POST'])
def quit_app():
    """处理退出请求"""

    # 在生产环境中可能需要更优雅的方式来关闭服务器
    def shutdown_server():
        # 触发系统信号来关闭服务器
        signal.raise_signal(signal.SIGTERM)

    # 安排在返回响应后关闭
    # 使用定时器避免在响应前关闭
    from threading import Timer
    timer = Timer(1, shutdown_server)
    timer.start()

    return jsonify({"status": "shutting_down"})


if __name__ == '__main__':
    print("AI聊天服务已启动。访问 http://localhost:5000")
    print("前端页面: 打开chat.html文件")
    print("按Ctrl+C退出服务")

    try:
        # 启动Flask服务器
        app.run(debug=False, port=5000)
    except KeyboardInterrupt:
        print("服务已手动停止")
    finally:
        print("AI聊天服务已关闭")
        sys.exit(0)